package main

import (
	"fmt"
	"gitee.com/phpdi/beehelp/clients/util"
	"github.com/360EntSecGroup-Skylar/excelize"
	"io/ioutil"
	"log"
	"os"
	"regexp"
	"strings"
	"yungengxin2019/lwyapi/utils"
	utils2 "yungengxin2019/lwycommon/entity/console/utils"
)

func main() {

	var (
		clients    []util.Client
		err        error
		clientsMap map[string][]util.Client
	)

	clientsMap = make(map[string][]util.Client)

	if clients, err = getClientsFromCsv("ews.xlsx"); err != nil {
		log.Fatal(err)
	}

	for _, v := range clients {
		clientsMap[v.NetbarName] = append(clientsMap[v.NetbarName], v)

	}

	os.Mkdir("data", os.ModePerm)
	for k, v := range clientsMap {
		if err = data2Onc(fmt.Sprintf("data/%s.onc", k), v); err != nil {
			fmt.Println("data2Onc:", err)
		}
	}

}

func getClientsFromCsv(file string) (res []util.Client, err error) {
	xlsx, err := excelize.OpenFile(file)
	rows := xlsx.GetRows("Sheet1")

	pinyin := utils2.NewPinyinService()

	reg := regexp.MustCompile("^[0-9]+$")

	for _, row := range rows {

		if len(row) < 9 {
			continue
		}

		if row[0] == "网吧" {
			continue
		}
		item := util.Client{
			NetbarName: row[0],
			GroupName:  row[1],
			Name:       row[2],
			IPAddr:     row[3],
			Mask:       row[4],
			Gateway:    row[5],
			Mac:        row[6],
			DNS1:       row[7],
			DNS2:       row[8],
		}

		item.MachineAlias = item.Name

		netbarName := strings.ToUpper(pinyin.Initials(item.NetbarName))

		if reg.MatchString(item.Name) {
			if netbarName != "" {
				item.Name = fmt.Sprintf("%s_%s", netbarName, item.Name)

			} else {
				item.Name = fmt.Sprintf("%s_%s", item.NetbarName, item.Name)
			}
		}

		if item.GroupName == "默认组" || item.GroupName == "" {
			item.GroupName = "默认分组"
		}

		res = append(res, item)
	}

	return

}

func data2Onc(file string, data []util.Client) (err error) {
	onc := utils.NewOncUtil().SetNoCareFields("NetbarName").SetPks("Mac")
	content := onc.Slice2Onc(data)
	return ioutil.WriteFile(file, content, os.ModePerm)
}
